﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IPC.Server
{
    public class NamedPipeThread
    {
        string PipeName { get; set; }
        public NamedPipeThread(string pipename)
        {
            PipeName = pipename;
        }
        public delegate void Recive(string str, NamedPipeServer server);
        public Recive? OnReceive { get; set; }
        public Task Run()
        {
            return Task.Run(() => {
                var server = new NamedPipeServer();
                using (var pipe = server.CreatPipeServer(PipeName))
                {
                    pipe.WaitForConnection();

                    while (true)
                    {
                        var str = server.Receive();
                        if (!string.IsNullOrEmpty(str))
                        {
                            Console.WriteLine(str);
                            if (str == "Exit")
                            {
                                break;
                            }
                            OnReceive?.Invoke(str, server);
                        }
                    }
                }
                Run();
            });
        }
    }
}
